package com.gec.component;

import com.gec.component.HttpServlet;
import com.gec.component.HttpServletRequest;
import com.gec.component.HttpServletResponse;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class DefaultServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp)
            throws IOException {
        String resPath = req.getResPath();
        //{1}去除第一个斜杠
        resPath = resPath.substring(1); //结果: login.htm
        //{2} "/" ---> "\" [windows路径符]
        resPath = resPath.replace("/", "\\");
        //{3}拼接文件的路径。
        String file = WebContainer.basePath + resPath;

        //{4}获取扩展名
        String extName = getExtName(resPath);
        //{5}获取 MIME
        String mime = getMIME(extName);
        //{6}设置响应头部 mime
        resp.setContentType( mime );
        //{7}读取文件数据。
        byte[] fileData = getFileData( file );
        //{8}把全部数据写入流中。
        resp.getWriter().write( fileData );
    }

    //{ps}获取文件的数据 (注意: 文件不能过大)
    private byte[] getFileData(String path)
            throws IOException{
        InputStream fis = new FileInputStream(path);
        //{2}创建一个与文件同尺寸的缓冲区。
        byte[] buff = new byte[ fis.available() ];
        //{3}读取数据到　buff.
        fis.read( buff );
        return buff;
    }

    //resPath = /index.htm
    private String getExtName(String resPath){
        int index = resPath.lastIndexOf(".");
        if( index!=-1 ){
            return resPath.substring(
                    index+1,resPath.length());
        }else{
            return resPath;
        }
    }

    Map<String,String> mimes = new HashMap();
    {
        mimes.put("htm", "text/html");
        mimes.put("html", "text/html");
        mimes.put("css", "text/css");
        mimes.put("js", "text/js");
        mimes.put("jpg", "image/jpg");
        mimes.put("png", "image/png");
    }
    private String getMIME(String extName){
        return mimes.get(extName);
    }


    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws IOException { }
}
